package com.yiba.logutils.save.impl;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;

import com.yiba.logutils.LogUtils;
import com.yiba.logutils.YBLogConstants;
import com.yiba.logutils.executor.ExecutorDispatcher;
import com.yiba.logutils.help.PermissionHelper;
import com.yiba.logutils.save.ILogRecorder;
import com.yiba.logutils.save.ILogWriter;
import com.yiba.logutils.utils.AppUtils;
import com.yiba.logutils.utils.DeviceUtils;
import com.yiba.logutils.utils.Logs;

import java.util.List;

public class LogRecorder implements ILogRecorder {


    private LogFormatter logFormatter;
    private ILogWriter logWriter;
    private Handler handler = new Handler(Looper.getMainLooper());
    private Context mContext;
    public  String dirPath;
    private String cipherKey;

    public LogRecorder(Context context) {
        this.mContext = context;
        this.logFormatter = new LogFormatter();
        ExecutorDispatcher.getInstance().executeRecord(new Runnable() {
            @Override
            public void run() {
                if (!PermissionHelper.hasWriteAndReadStoragePermission(mContext)) {
                    Logs.e("no permission for init");
                    return;
                }
                tryInitLogWriter();
            }
        });
    }

    private void tryInitLogWriter() {
        if (null != logWriter) {
            return;
        }
        dirPath =  LogUtils.getInstance().getROOT();
        Logs.i("LogRecorder-->tryInitLogWriter,dirPath:" + dirPath);

        if (!YBLogConstants.ENABLEBACKUP) {
            try {
                MmapLogWriter mmapLogWriter = new MmapLogWriter();
                String basicInfo = logFormatter.format(getBasicInfo(), false);
                mmapLogWriter.init(mContext, basicInfo, dirPath, cipherKey);
                logWriter = mmapLogWriter;
            } catch (Throwable ex) {
                ex.printStackTrace();
                initNormalLogWriter();
            }
        } else {
            initNormalLogWriter();
        }

    }

    private void initNormalLogWriter() {

    }

    private String getBasicInfo() {
        StringBuilder stringBuilder = new StringBuilder();
        ApplicationInfo ai = mContext.getApplicationInfo();
        PackageManager pm = mContext.getPackageManager();
        try {
            PackageInfo pi = pm.getPackageInfo(ai.packageName, 0);
            stringBuilder.append("Version Code: ").append(pi.versionCode);
            stringBuilder.append("Version Name: ").append(pi.versionName);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        stringBuilder.append("Android")
                .append("#*")
                .append(AppUtils.getCurProcessName(mContext))
                .append(YBLogConstants.INTERNAL_SEPERATOR)
                .append(AppUtils.getVersionName(mContext))
                .append(YBLogConstants.INTERNAL_SEPERATOR)
                .append("~")
                .append(YBLogConstants.INTERNAL_SEPERATOR)
                .append(DeviceUtils.getDeviceInfo())
                .append(YBLogConstants.INTERNAL_SEPERATOR)
                .append("手机是否root"+(DeviceUtils.isRoot() ? 1 : 0))
                .append(YBLogConstants.INTERNAL_SEPERATOR)
                .append("DEVICE INFORMATION")
                .append("BOOTLOADER: ").append(Build.BOOTLOADER)
                .append(YBLogConstants.INTERNAL_SEPERATOR)
                .append("SDK: ").append(Build.VERSION.SDK)
                .append(YBLogConstants.INTERNAL_SEPERATOR)
                .append("BRAND: ").append(Build.BRAND)
                .append(YBLogConstants.INTERNAL_SEPERATOR)
                .append("MODEL: ").append(Build.MODEL)
                .append(YBLogConstants.INTERNAL_SEPERATOR)
                .append("DEVICE: ").append(Build.DEVICE)
                .append(YBLogConstants.INTERNAL_SEPERATOR)
                .append("HARDWARE: ").append(Build.HARDWARE);
        return stringBuilder.toString();
    }





    @Override
    public void log(final String tag, final String msg, final boolean encryptFlag) {
        if (TextUtils.isEmpty(tag) || TextUtils.isEmpty(msg)) {
            return;
        }
        ExecutorDispatcher.getInstance().executeRecord(new Runnable() {
            @Override
            public void run() {
                if (!PermissionHelper.hasWriteAndReadStoragePermission(mContext)) {
                    Logs.e("no permission for log");
                    return;
                }
                checkInitAndRecordSync(logFormatter.format(msg, encryptFlag), encryptFlag);
            }
        });
    }

    @Override
    public void log(String tag, List<String> msgFieldList, boolean cryptFlag) {

    }

    @Override
    public void logToJson(String tag, Object o, boolean encryptFlag) {

    }

    private void checkInitAndRecordSync(String msgContent, boolean encryptFlag) {
        if (TextUtils.isEmpty(msgContent)) {
            return;
        }
        tryInitLogWriter();
        try {
            logWriter.write(msgContent, encryptFlag);
        } catch (Throwable ex) {
            ex.printStackTrace();
        } finally {
            msgContent = null;
        }
    }
}
